package cn.dankal.flyaudio.friend;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.kongzue.dialog.listener.InputDialogOkButtonClickListener;
import com.kongzue.dialog.v2.InputDialog;
import com.kongzue.dialog.v2.SelectDialog;
import com.kongzue.dialog.v2.TipDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.base.recyclerview.OnRvItemClickListener;
import cn.dankal.basiclib.common.bus.LiveDataBusConstants;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.JMessageToastUtils;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.GroupMembersAdapter;
import cn.dankal.flyaudio.entity.Event;
import cn.dankal.flyaudio.entity.EventType;
import cn.dankal.flyaudio.personal.PersonalProfileActivity;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.DownloadAvatarCallback;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.callback.RequestCallback;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.GroupMemberInfo;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class GroupInfoActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView membersView;

    private Switch messageSwitch;
    private Switch setTopView;
    private TextView groupNameView;

    private GroupMembersAdapter adapter;

    private long mGroupId;
    private List<UserInfo> mMemberInfoList = new ArrayList<>();
    private GroupInfo mGroupInfo;
    private boolean isOwner = false;
    private TextView deleteView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_group_info;
    }

    @Override
    protected void initComponents() {
        addSingleTitleBar("聊天详情");
        membersView = findViewById(R.id.members_recycler);
        adapter = new GroupMembersAdapter();
        messageSwitch = findViewById(R.id.switch_message);
        setTopView = findViewById(R.id.switch_top);
        groupNameView = findViewById(R.id.tv_group_name);
        deleteView = findViewById(R.id.sl_delete_group);
        findViewById(R.id.sl_delete_group).setOnClickListener(this);
        findViewById(R.id.rl_group_manager_layout).setOnClickListener(this);
        findViewById(R.id.rl_group_manager_verify).setOnClickListener(this);
        findViewById(R.id.rl_group_name).setOnClickListener(this);
        findViewById(R.id.rl_qrcode).setOnClickListener(this);
        findViewById(R.id.rl_report).setOnClickListener(this);
        membersView.setLayoutManager(new GridLayoutManager(this, 5));
        membersView.setAdapter(adapter);

        adapter.setOnRvItemClickListener(new OnRvItemClickListener<UserInfo>() {
            @Override
            public void onItemClick(View v, int position, UserInfo data) {
                if ("-----1".equals(data.getNickname())) {
                    Intent intent = new Intent(GroupInfoActivity.this, PickContractPersonActivity.class);
                    intent.putExtra(FlyApplication.GROUP_ID, mGroupId);
                    intent.putExtra("type", PickContractPersonActivity.TYPE_DELETE_GROUP_MEMBERS);
                    startActivity(intent);
                } else {
                    if (TextUtils.isEmpty(data.getUserName())) {
                        //添加成员

                        Intent intent = new Intent(GroupInfoActivity.this, PickContractPersonActivity.class);
                        intent.putExtra(FlyApplication.GROUP_ID, mGroupId);
                        intent.putExtra("type", PickContractPersonActivity.TYPE_ADD_GROUP_MEMBERS);
                        startActivity(intent);

                    } else {
                        Intent intent = new Intent(GroupInfoActivity.this, PersonalProfileActivity.class);
                        intent.putExtra("userId", data.getUserName());
                        startActivity(intent);
                    }
                }
            }
        });
        LiveEventBus.get(LiveDataBusConstants.UPDATE_GROUP_MEMBERS_INFO, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                initData();
            }
        });
        initData();
    }

    private void initData() {
        mGroupId = getIntent().getLongExtra(FlyApplication.GROUP_ID, 0);
        final Conversation conv = JMessageClient.getGroupConversation(mGroupId);
        mGroupInfo = (GroupInfo) conv.getTargetInfo();
        groupNameView.setText(mGroupInfo.getGroupName());
        if (TextUtils.isEmpty(mGroupInfo.getGroupName())) {
            ToastUtils.showShort("无效群组");
            finish();
        }
//        conv.updateConversationExtra("11");
//        getGroupMembers();

        messageSwitch.setChecked(mGroupInfo.isGroupBlocked() == 1);
        messageSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mGroupInfo.setBlockGroupMessage(isChecked ? 1 : 0, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        JMessageToastUtils.errorToast(i);
                    }
                });
            }
        });
        Conversation cov = JMessageClient.getGroupConversation(mGroupId);
        String extra = cov.getExtra();
        setTopView.setChecked(!TextUtils.isEmpty(extra));
        setTopView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    conv.updateConversationExtra("0");
                    LiveEventBus.get(LiveDataBusConstants.GROUP_MESSAGE_SET_TOP, Conversation.class).post(conv);
                } else {
                    conv.updateConversationExtra("");
                    LiveEventBus.get(LiveDataBusConstants.GROUP_MESSAGE_CANCEL_SET_TOP, Conversation.class).post(conv);
                }
            }
        });
        //设置群主头像和名字
        JMessageClient.getUserInfo(mGroupInfo.getGroupOwner(), new GetUserInfoCallback() {
            @Override
            public void gotResult(int i, String s, UserInfo userInfo) {
                if (i == 0) {
                    if (userInfo.getAvatarFile() != null) {
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getGroupMembers();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.rl_group_name:
                if (!isOwner) {
                    TipDialog.show(GroupInfoActivity.this, "您不是群主，无法修改群名称");
                    return;
                }
                InputDialog.show(GroupInfoActivity.this, "提示", "请输入群名称", "确定", new InputDialogOkButtonClickListener() {
                    @Override
                    public void onClick(Dialog dialog, String inputText) {
                        if (TextUtils.isEmpty(inputText.trim())) {
                            ToastUtils.showShort("群名称不能为空!");
                            return;
                        }
                        mGroupInfo.updateName(inputText, new BasicCallback() {
                            @Override
                            public void gotResult(int i, String s) {
                                groupNameView.setText(inputText);
                                dialog.dismiss();
                            }
                        });
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                break;
            case R.id.rl_report:
                Intent reportIntent = new Intent(this, ReportActivity.class);
                reportIntent.putExtra(FlyApplication.TARGET_ID, mGroupId);
                startActivity(reportIntent);
                break;
            case R.id.rl_group_manager_layout:
                Intent intent = new Intent(this, GroupManagerActivity.class);
                intent.putExtra("isGroupManager", isOwner);
                intent.putExtra("group_id", mGroupId);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.rl_group_manager_verify:
                Intent verifyGroupIntent = new Intent(this, GroupVerifyActivity.class);
//                intent.putExtra("isGroupManager", isOwner);
                verifyGroupIntent.putExtra("group_id", mGroupId);
                ActivityUtils.startActivity(verifyGroupIntent);
                break;
            case R.id.sl_delete_group:
                if (isOwner) {
                    SelectDialog.show(GroupInfoActivity.this, "提示", "是否要删除", "确定", (dialog, which) -> {
                        showLoadingDialog();
                        JMessageClient.adminDissolveGroup(mGroupId, new BasicCallback() {
                            @Override
                            public void gotResult(int status, String s) {
                                if (status == 0) {
                                    Conversation conv = JMessageClient.getGroupConversation(mGroupId);
                                    EventBus.getDefault().post(new Event.Builder().setType(EventType.deleteConversation)
                                            .setConversation(conv)
                                            .build());
//                                    JMessageClient.deleteGroupConversation(mGroupId);
                                    dismissLoadingDialog();
                                    ActivityUtils.finishActivity(ChatActivity.class);
                                    finishActivity();
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtils.showShort("退出失败");
                                }
                            }
                        });
                    }, "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                } else {
                    SelectDialog.show(GroupInfoActivity.this, "提示", "是否要退出", "确定", (dialog, which) -> {
                        showLoadingDialog();
                        JMessageClient.exitGroup(mGroupId, new BasicCallback() {
                            @Override
                            public void gotResult(final int status, final String desc) {
                                dismissLoadingDialog();
                                if (status == 0) {
                                    Conversation conv = JMessageClient.getGroupConversation(mGroupId);
                                    EventBus.getDefault().post(new Event.Builder().setType(EventType.deleteConversation)
                                            .setConversation(conv)
                                            .build());
//                                    JMessageClient.deleteGroupConversation(mGroupId);
                                    dismissLoadingDialog();
                                    ActivityUtils.finishActivity(ChatActivity.class);
                                    finishActivity();
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtils.showShort("退出失败");
                                }
                            }
                        });
                    }, "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                }

                break;
            case R.id.rl_qrcode:
                Intent intent1 = new Intent(this, GroupQRCodeActivity.class);
                intent1.putExtra("group_id", mGroupId);
                ActivityUtils.startActivity(intent1);
                break;
        }
    }

    private void timeClose() {
        Observable.timer(1000, TimeUnit.MILLISECONDS)
                .subscribeOn(io.reactivex.schedulers.Schedulers.io())
                .unsubscribeOn(io.reactivex.schedulers.Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {

                    }
                });
    }

    private void getGroupMembers() {
        mMemberInfoList.clear();
        JMessageClient.getGroupMembers(mGroupId, new RequestCallback<List<GroupMemberInfo>>() {
            @Override
            public void gotResult(int i, String s, List<GroupMemberInfo> groupMemberInfos) {
                if (i == 0) {
                    //获取群成员成功
                    for (GroupMemberInfo groupMemberInfo : groupMemberInfos) {
                        if (groupMemberInfo.getType() == GroupMemberInfo.Type.group_owner) {
                            mMemberInfoList.add(0, groupMemberInfo.getUserInfo());
                        } else {
                            mMemberInfoList.add(groupMemberInfo.getUserInfo());
                        }
                    }
                    setInfoData();
                } else {
                    JMessageToastUtils.errorToast(i);

                }
            }
        });

        List<GroupMemberInfo> groupMemberInfos = mGroupInfo.getGroupMemberInfos();
        for (GroupMemberInfo groupMemberInfo : groupMemberInfos) {
            if (TextUtils.equals(groupMemberInfo.getUserInfo().getUserName(), JMessageClient.getMyInfo().getUserName())) {
                if (groupMemberInfo.getType() == GroupMemberInfo.Type.group_owner) {
                    //群组
                    isOwner = true;
                    deleteView.setText("解散并删除");
                } else if (groupMemberInfo.getType() == GroupMemberInfo.Type.group_member) {
                    //群员
                    findViewById(R.id.rl_group_manager_layout).setVisibility(View.GONE);
                    findViewById(R.id.rl_group_manager_verify).setVisibility(View.GONE);
                    deleteView.setText("删除并退出");
                } else {
                    //管理员
                    deleteView.setText("删除并退出");
                }
            }
        }
    }

    private void setInfoData() {
        if (StringUtils.equals(mGroupInfo.getOwnerMemberInfo().getUserInfo().getUserName(), JMessageClient.getMyInfo().getUserName())) {
            //群主
            mMemberInfoList.add(new UserInfo() {
                @Override
                public String getNotename() {
                    return null;
                }

                @Override
                public String getNoteText() {
                    return null;
                }

                @Override
                public long getBirthday() {
                    return 0;
                }

                @Override
                public File getAvatarFile() {
                    return null;
                }

                @Override
                public void getAvatarFileAsync(DownloadAvatarCallback downloadAvatarCallback) {

                }

                @Override
                public void getAvatarBitmap(GetAvatarBitmapCallback getAvatarBitmapCallback) {

                }

                @Override
                public File getBigAvatarFile() {
                    return null;
                }

                @Override
                public void getBigAvatarBitmap(GetAvatarBitmapCallback getAvatarBitmapCallback) {

                }

                @Override
                public int getBlacklist() {
                    return 0;
                }

                @Override
                public int getNoDisturb() {
                    return 0;
                }

                @Override
                public boolean isFriend() {
                    return false;
                }

                @Override
                public String getAppKey() {
                    return null;
                }

                @Override
                public void setUserExtras(Map<String, String> map) {

                }

                @Override
                public void setUserExtras(String s, String s1) {

                }

                @Override
                public void setBirthday(long l) {

                }

                @Override
                public void setNoDisturb(int i, BasicCallback basicCallback) {

                }

                @Override
                public void removeFromFriendList(BasicCallback basicCallback) {

                }

                @Override
                public void updateNoteName(String s, BasicCallback basicCallback) {

                }

                @Override
                public void updateNoteText(String s, BasicCallback basicCallback) {

                }

                @Override
                public String getDisplayName() {
                    return null;
                }
            });

            UserInfo userInfo = new UserInfo() {
                @Override
                public String getNotename() {
                    return null;
                }

                @Override
                public String getNoteText() {
                    return null;
                }

                @Override
                public long getBirthday() {
                    return 1;
                }

                @Override
                public File getAvatarFile() {
                    return null;
                }

                @Override
                public void getAvatarFileAsync(DownloadAvatarCallback downloadAvatarCallback) {

                }

                @Override
                public void getAvatarBitmap(GetAvatarBitmapCallback getAvatarBitmapCallback) {

                }

                @Override
                public File getBigAvatarFile() {
                    return null;
                }

                @Override
                public void getBigAvatarBitmap(GetAvatarBitmapCallback getAvatarBitmapCallback) {

                }

                @Override
                public int getBlacklist() {
                    return 0;
                }

                @Override
                public int getNoDisturb() {
                    return 0;
                }

                @Override
                public boolean isFriend() {
                    return false;
                }

                @Override
                public String getAppKey() {
                    return null;
                }

                @Override
                public void setUserExtras(Map<String, String> map) {

                }

                @Override
                public void setUserExtras(String s, String s1) {

                }

                @Override
                public void setBirthday(long l) {

                }

                @Override
                public void setNoDisturb(int i, BasicCallback basicCallback) {

                }

                @Override
                public void removeFromFriendList(BasicCallback basicCallback) {

                }

                @Override
                public void updateNoteName(String s, BasicCallback basicCallback) {

                }

                @Override
                public void updateNoteText(String s, BasicCallback basicCallback) {

                }

                @Override
                public String getDisplayName() {
                    return null;
                }
            };
            userInfo.setNickname("-----1");
            mMemberInfoList.add(userInfo);
        }

        adapter.addDatas(mMemberInfoList, true);
    }
}
